package cn.rengy.web.framework.wxmp.component.token;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.rengy.tpa.wxmp.exception.WeChatException;
import cn.rengy.web.framework.sql.DbService;
/**
 * 第三方平台的token的redis缓存实现
 * @author rengy
 *
 */
@ConditionalOnProperty(name = "spring.cache.type", havingValue = "redis", matchIfMissing = false)
@Service(value="componentTokenService")
public class RedisComponentTokenService implements ComponentTokenService{
	private static Logger logger = LoggerFactory.getLogger(RedisComponentTokenService.class);
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	@Autowired
	private DbService dbService;
	@Autowired
	private RedisComponentTokenRefreshService redisComponentTokenRefreshService;
	
	
	/**
	 * 获取第三方平台的token
	 * @param component_appid
	 * @return
	 * @throws Exception 
	 */
	public String accessToken(String component_appid) throws WeChatException{
		String key=  ACCESS_TOKEN_KEY.concat(component_appid);
		/**
		 * 1.从缓存中获取
		 * 2.有 返回
		 * 3.无 刷新缓存 再次获取返回
		 */
		String token=null;
		ValueOperations<String, String> vo=stringRedisTemplate.opsForValue();
		token=vo.get(key);
		logger.debug("从缓存中获取{}的accessToken结果{}",key,token);
		if(token==null){
			redisComponentTokenRefreshService.refresh(component_appid);
			token=vo.get(key);
		}
		if(token==null){
			throw new WeChatException(-1,"获取token失败");
		}
		return token;
	}
	
	/**
	 * 删除第三方平台的token缓存，token不可用时调用
	 * @param component_appid
	 */
	@Transactional()
	public void evictAccessToken(String component_appid,String value){
		Map<String,Object> tokenMap=this.dbService.queryForMap("lock_wx_component_token", component_appid);
		if(tokenMap!=null){
			String key=  ACCESS_TOKEN_KEY.concat(component_appid);
			ValueOperations<String, String> vo=stringRedisTemplate.opsForValue();
			String token=vo.get(key);
			if(token!=null&&token.equals(value)){
				logger.info("删除{}的componentAccessToken",component_appid);
				stringRedisTemplate.delete(key);
			}
		}
	}

	@Override
	public String preAuthCode(String component_appid) throws WeChatException {
		String token=null;
		String key= PRE_AUTH_CODE_KEY.concat(component_appid);
		ValueOperations<String, String> vo=stringRedisTemplate.opsForValue();
		token=vo.get(key);
		logger.debug("从缓存中获取{}的preAuthCode结果{}",key,token);
		if(token==null){
			redisComponentTokenRefreshService.refreshPreAuthCode(component_appid);
			token=vo.get(key);
		}
		if(token==null){
			throw new WeChatException("获取preAuthCode失败");
		}
		return token;
	}
	/**
	 * 授权方accessToken
	 */
	@Override
	public String authAccessToken(String appid) throws WeChatException {
		String key=APP_ACCESS_TOKEN_KEY.concat(appid);
		/**
		 * 1.从缓存中获取
		 * 2.有 返回
		 * 3.无 刷新缓存 再次获取返回
		 */
		String token=null;
		ValueOperations<String, String> vo=stringRedisTemplate.opsForValue();
		token=vo.get(key);
		logger.debug("从缓存中获取授权方令牌{}的authAccessToken结果{}",key,token);
		if(token==null){
			redisComponentTokenRefreshService.refreshAuthAccessToken(appid);
			token=vo.get(key);
		}
		if(token==null){
			throw new WeChatException(-1,"获取token失败");
		}
		return token;
	}
	
	@Override
	public void evictAuthAccessToken(String appid, String value) {
		//Map<String,Object> tokenMap=this.dbService.queryForMap("lock_wx_app_token", appid);
		//if(tokenMap!=null){
		String key=  APP_ACCESS_TOKEN_KEY.concat(appid);
		ValueOperations<String, String> vo=stringRedisTemplate.opsForValue();
		String token=vo.get(key);
		if(token!=null&&token.equals(value)){
			logger.info("删除{}的AuthAccessToken",appid);
			stringRedisTemplate.delete(key);
		}
		//}
		
	}

	@Override
	public String jsApiTicket(String appid) throws WeChatException {
		String token=null;
		String key=JSAPITICKET_KEY.concat(appid);
		ValueOperations<String, String> vo=stringRedisTemplate.opsForValue();
		token=vo.get(key);
		if(token==null){
			redisComponentTokenRefreshService.refreshJsApiTicket(appid);
			token=vo.get(key);
		}
		if(token==null){
			throw new WeChatException("获取jsApiTicket失败");
		}
		return token;
	}

	@Override
	public void evictJsApiTicket(String appid, String value) {
		String key=JSAPITICKET_KEY.concat(appid);
		ValueOperations<String, String> vo=stringRedisTemplate.opsForValue();
		String token=vo.get(key);
		if(token!=null&&token.equals(value)){
			logger.info("删除{}的JsApiTicket",appid);
			stringRedisTemplate.delete(key);
		}
	}

}
